import { Provide, Inject } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not } from 'typeorm';
import { TodoEntity } from '../entity/todo';
import { ProjectMemberEntity } from '../../project/entity/member';
import { ProjectEntity } from '../../project/entity/project';
import { Context } from '@midwayjs/koa';

/**
 * 待办事项
 */
@Provide()
export class TodoService extends BaseService {
    @Inject()
    ctx: Context;

    @InjectEntityModel(TodoEntity)
    todoEntity: Repository<TodoEntity>;

    @InjectEntityModel(ProjectMemberEntity)
    projectMemberEntity: Repository<ProjectMemberEntity>;

    @InjectEntityModel(ProjectEntity)
    projectEntity: Repository<ProjectEntity>;

    /**
     * 新增前检查
     */
    async modifyBefore(param: any) {
        if (this.ctx.url.endsWith('/add')) {
            // 如果请求的是新增todo, 则检查是否为项目管理员
            const member = await this.projectMemberEntity.findOne({
                where: {
                    projectId: param.projectId,
                    userId: this.ctx.user.id
                }
            });
            if (!member) {
                console.log('modifyBefore_ param:', param, 'ctx.user.id:', this.ctx.user.id);
                throw new Error('只有项目管理员才能创建待办事项');
            }
        } else if (this.ctx.url.endsWith('/update')) {
            // 如果请求的是更新todo, 则检查是否为项目的管理员 或者为 todo 的执行者
            const managerMember = await this.projectMemberEntity.findOne({
                where: {
                    projectId: param.projectId,
                    userId: this.ctx.user.id
                }
            });
            const execMember = await this.todoEntity.findOne({
                where: {
                    id: param.id,
                    execUserId: this.ctx.user.id
                }
            });

            if (!managerMember && !execMember) {
                throw new Error('修改必须是项目管理员或者todo执行者');
            }
        }
    }

    async add(param: any) {
        param.createUserId = this.ctx.user.id;
        param.execUserId = this.ctx.user.id;
        return super.add(param);
    }

    /**
     * 增加待办事项总时长
     */
    async addTotalTime(todoId: number, minutes: number) {
        const todo = await this.todoEntity.findOne({
            where: { id: todoId }
        });
        if (!todo) {
            throw new Error('待办事项不存在');
        }

        // 更新待办事项时长
        await this.todoEntity.update(todoId, {
            totalTime: todo.totalTime + minutes
        });

        // 更新项目总时长
        const project = await this.projectEntity.findOne({
            where: { id: todo.projectId }
        });
        if (project) {
            await this.projectEntity.update(project.id, {
                totalTime: project.totalTime + minutes
            });
        }
    }

    /**
     * 更新待办事项状态
     */
    async updateStatus(id: number, status: number) {
        // 检查状态值是否合法
        if (![0, 1, 2].includes(status)) {
            throw new CoolCommException('状态值不合法');
        }

        const todo = await this.todoEntity.findOne({
            where: { id }
        });
        if (!todo) {
            throw new CoolCommException('待办事项不存在');
        }

        // 更新待办事项状态
        await this.todoEntity.update(id, {
            status,
            updateTime: new Date()
        });

        // 如果任务完成，检查项目中是否所有任务都已完成
        if (status === 2) {
            const unfinishedTodos = await this.todoEntity.count({
                where: {
                    projectId: todo.projectId,
                    status: Not(2)  // 未完成的任务
                }
            });

            // 如果没有未完成的任务，将项目状态更新为已完成
            if (unfinishedTodos === 0) {
                await this.projectEntity.update(todo.projectId, {
                    status: 1,  // 已完成
                    updateTime: new Date()
                });
            }
        }
    }
} 